#include <stdio.h>
#include <sched.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <time.h>
#include <sys/time.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include "motor_gpio.h"
int direction = 0;

//导出GPIO
static void export_gpio()
{
    int export_fd = open("/sys/class/gpio/export", O_WRONLY);
    if(export_fd < 0)
    {
        perror("open error");
        exit(0);
    }
    write(export_fd, "5", 1);
    write(export_fd, "6", 1);
    write(export_fd, "17", 2);
    write(export_fd, "27", 2);
    close(export_fd);
}

//设置GPIO的方向
static void set_gpio_direction()
{
    int direction_fd = open("/sys/class/gpio/gpio5/direction", O_WRONLY);
    write(direction_fd, "out", 3);
    close(direction_fd);

    direction_fd = open("/sys/class/gpio/gpio6/direction", O_WRONLY);
    write(direction_fd, "out", 3);
    close(direction_fd);

    direction_fd = open("/sys/class/gpio/gpio17/direction", O_WRONLY);
    write(direction_fd, "in", 2);
    close(direction_fd);

    direction_fd = open("/sys/class/gpio/gpio27/direction", O_WRONLY);
    write(direction_fd, "in", 2);
    close(direction_fd);
}

//设置方向为输入的GPIO的边缘触发方式，both表示上升沿和下降沿。poll
static void set_input_edge()
{
    int edge_fd = open("/sys/class/gpio/gpio17/edge", O_WRONLY);
    write(edge_fd, "both", 4);
    close(edge_fd);
    edge_fd = open("/sys/class/gpio/gpio27/edge", O_WRONLY);
    write(edge_fd, "both", 4);
    close(edge_fd);
}

//设置电机转向，0正1反
void set_motor_direction(int dir)
{
    if(dir == 0)
    {
        direction = 0;
        int value_fd = open("/sys/class/gpio/gpio5/value", O_WRONLY);
        write(value_fd, "0", 1);
        close(value_fd);
        value_fd = open("/sys/class/gpio/gpio6/value", O_WRONLY);
        write(value_fd, "1", 1);
        close(value_fd);
    }else
    {
        direction = 1;
        int value_fd = open("/sys/class/gpio/gpio5/value", O_WRONLY);
        write(value_fd, "1", 1);
        close(value_fd);
        value_fd = open("/sys/class/gpio/gpio6/value", O_WRONLY);
        write(value_fd, "0", 1);
        close(value_fd);
    }
}

//初始化GPIO
void init_gpio()
{
    export_gpio();
    set_gpio_direction();
    set_input_edge();
}

